package com.smoed.common.utilities;

import java.io.*;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public final class CompressionUtils {

    public synchronized static byte[] compressObject(Serializable data) {
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            ObjectOutputStream oos = null;
            try {
                oos = new ObjectOutputStream(new GZIPOutputStream(baos));
                oos.writeObject(data);
            } finally {
                if (oos != null) {
                    oos.close();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return baos.toByteArray();
    }

    public synchronized static Object decompressObject(byte[] bytes) {
        Object obj = null;
        try {
            ObjectInputStream ois = null;
            try {
                final ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
                ois = new ObjectInputStream(new GZIPInputStream(bais));
                obj = ois.readObject();
            } finally {
                if (ois != null) {
                    ois.close();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        return obj;
    }
}
